package com.newdjk.newdoctor.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.newdjk.newdoctor.BuildConfig;
import com.newdjk.newdoctor.MyApplication;
import com.newdjk.newdoctor.R;
import com.newdjk.newdoctor.adapter.MinFunctionAdapter;
import com.newdjk.newdoctor.base.BasicFragment;
import com.newdjk.newdoctor.constants.AppConfig;
import com.newdjk.newdoctor.constants.EnvironmentManager;
import com.newdjk.newdoctor.dialog.SwitchEnvironmentDialog;
import com.newdjk.newdoctor.entity.AppLicationEntity;
import com.newdjk.newdoctor.net.BaseComPleteObserver;
import com.newdjk.newdoctor.net.NetServices;
import com.newdjk.newdoctor.ui.AboutUsActivity;
import com.newdjk.newdoctor.ui.ChangePasswordActivity;
import com.newdjk.newdoctor.ui.LoginActivity;
import com.newdjk.newdoctor.ui.OrganizationInfoActivity;
import com.newdjk.newdoctor.ui.RenzhengActivity;
import com.newdjk.newdoctor.ui.SuggestionActivity;
import com.newdjk.newdoctor.ui.SwitchShopActivity;
import com.newdjk.newdoctor.ui.WebViewActivity;
import com.newdjk.newdoctor.utils.AppLicationUtils;
import com.newdjk.newdoctor.utils.CleanMessageUtil;
import com.newdjk.newdoctor.utils.Contants;
import com.newdjk.newdoctor.utils.Event;
import com.newdjk.newdoctor.utils.GlideUtils;
import com.newdjk.newdoctor.utils.LogOutUtil;
import com.newdjk.newdoctor.utils.RxBus;
import com.newdjk.newdoctor.utils.SpUtils;
import com.newdjk.newdoctor.utils.ToastUtil;
import com.newdjk.newdoctor.view.CircleImageView;
import com.newdjk.newdoctor.view.ItemView;
import com.newdjk.okhttp.RetrofitFactory;
import com.newdjk.okhttp.entity.BaseEntity;
import com.newdjk.okhttp.entity.DoctorInfoEntity;
import com.newdjk.okhttp.entity.H5LoginEntity;
import com.newdjk.okhttp.entity.MedicationCompanyEntity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class MineFragment extends BasicFragment implements SwipeRefreshLayout.OnRefreshListener {

    private static final String TAG = "MineFragment";
    @BindView(R.id.tv_name)
    TextView tvName;

    @BindView(R.id.im_doctor)
    CircleImageView imDoctor;
    @BindView(R.id.tv_doctor_renzheng)
    TextView tvDoctorRenzheng;
    @BindView(R.id.login_out)
    AppCompatButton loginOut;
    @BindView(R.id.lv_wodechufang)
    LinearLayout lvWodechufang;
    @BindView(R.id.lv_youxuantuijian)
    LinearLayout lvYouxuantuijian;
    @BindView(R.id.lv_jianchadan)
    LinearLayout lvJianchadan;
    @BindView(R.id.change_password)
    ItemView changePassword;
    @BindView(R.id.about_us)
    ItemView aboutUs;
    @BindView(R.id.item_advice)
    ItemView itemAdvice;
    @BindView(R.id.item_callphone)
    ItemView itemCallphone;
    @BindView(R.id.clear_cache)
    ItemView clearCache;
    @BindView(R.id.item_renzheng)
    ItemView itemRenzheng;
    @BindView(R.id.lv_shouyaojilu)
    LinearLayout lvShouyaojilu;
    @BindView(R.id.siwtch_environment)
    ItemView siwtchEnvironment;
    @BindView(R.id.lv_siwtch_environment)
    LinearLayout lvSiwtchEnvironment;
    @BindView(R.id.recyleview)
    RecyclerView recyleview;
    @BindView(R.id.swipeLayoout)
    SwipeRefreshLayout swipeLayoout;
    @BindView(R.id.tv_switch_shop)
    TextView tvSwitchShop;
    @BindView(R.id.medical_shopmenmber_manage)
    ItemView medicalShopmenmberManage;
    @BindView(R.id.line_yaodian)
    View lineYaodian;
    @BindView(R.id.tv_shop)
    TextView tvShop;
    @BindView(R.id.jigou_line)
    View jigouLine;
    @BindView(R.id.lv_shop)
    LinearLayout lvShop;
    @BindView(R.id.tv_order_title)
    TextView tvOrderTitle;
    private String totalCacheSize;
    private MinFunctionAdapter mFunctionAdapter;
    private List<AppLicationEntity> listall = new ArrayList<>();
    private Observable<Boolean> loginObservable;
    private Observable<Boolean> switchShopObservable;

    @Override
    protected int initViewResId() {
        return R.layout.fragment_mine;
    }

    @SuppressLint("CheckResult")
    @Override
    protected void initView() {
        //显示缓存数据的大小
        getCache();
        setCatch();
        initRecyleview();
        if (BuildConfig.IS_DEBUG) {
            lvSiwtchEnvironment.setVisibility(View.VISIBLE);
            if (EnvironmentManager.isDebug(getContext())) {
                siwtchEnvironment.setRightText("(测试环境)");

            } else {
                siwtchEnvironment.setRightText("(正式环境)");
            }

        }
        loginObservable = RxBus.get().register(Event.Login_success);
        switchShopObservable = RxBus.get().register(Event.Switch_shop_success);

        loginObservable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                Log.d(TAG, "MineFragment 更新订单列表");
                QueryDoctorIdentify();
                GetMedicationCompanyByDrId();
            }
        });
        switchShopObservable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                Log.d(TAG, "MineFragment 更新订单列表");
                QueryDoctorIdentify();
                GetMedicationCompanyByDrId();
            }
        });

    }

    private void initRecyleview() {

        GridLayoutManager mManagerLayout = new GridLayoutManager(mContext, 3);
        recyleview.setLayoutManager(mManagerLayout);
        mFunctionAdapter = new MinFunctionAdapter(listall);
        recyleview.setAdapter(mFunctionAdapter);
        if (mFunctionAdapter != null) {
            mFunctionAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                    //   ToastUtil.setToast(listall.get(position).getAppDesc());

                    tabitemClick(listall.get(position).getAppDesc());

                }
            });
        }
    }

    private void tabitemClick(String appDesc) {

        switch (appDesc) {
            case "采购订单":
                Intent caigou = new Intent(mContext, WebViewActivity.class);
                caigou.putExtra("type", 20);
                mContext.startActivity(caigou);
                break;
            case "售药记录":
                Intent shouyao = new Intent(mContext, WebViewActivity.class);
                shouyao.putExtra("type", 19);
                mContext.startActivity(shouyao);
                break;
            case "优选推荐":
                Intent intentadvice = new Intent(mContext, WebViewActivity.class);
                intentadvice.putExtra("type", 16);
                mContext.startActivity(intentadvice);
                break;
            case "坐诊订单":
                //  int a=5/0;
                Intent applyzuozhen = new Intent(getContext(), WebViewActivity.class);
                applyzuozhen.putExtra(Contants.TYPE, 3);
                getContext().startActivity(applyzuozhen);
                break;
            case "医废申请订单":
                Intent yifei = new Intent(getContext(), WebViewActivity.class);
                yifei.putExtra(Contants.TYPE, 13);
                getContext().startActivity(yifei);

                break;
            case "处方申请记录":
                Intent chufang = new Intent(getContext(), WebViewActivity.class);
                chufang.putExtra(Contants.TYPE, 17);
                getContext().startActivity(chufang);
                break;
            case "服务包推荐记录":
                Intent servicepack = new Intent(getContext(), WebViewActivity.class);
                servicepack.putExtra(Contants.TYPE, 30);
                getContext().startActivity(servicepack);
                break;
            case "处方套餐订单":
                Intent tiaopei = new Intent(getContext(), WebViewActivity.class);
                tiaopei.putExtra(Contants.TYPE, 37);
                getContext().startActivity(tiaopei);
                break;
        }
    }

    private void setCatch() {

        if (TextUtils.isEmpty(totalCacheSize)) {
            clearCache.setRightText("");
        } else {
            clearCache.setRightText(totalCacheSize);
        }
    }

    @Override
    protected void initListener() {
        loginOut.setOnClickListener(this::otherViewClick);

        tvDoctorRenzheng.setOnClickListener(this::otherViewClick);
        changePassword.setOnClickListener(this::otherViewClick);
        aboutUs.setOnClickListener(this::otherViewClick);
        itemAdvice.setOnClickListener(this::otherViewClick);
        itemCallphone.setOnClickListener(this::otherViewClick);
        clearCache.setOnClickListener(this::otherViewClick);
        itemRenzheng.setOnClickListener(this::otherViewClick);
        siwtchEnvironment.setOnClickListener(this::otherViewClick);
        swipeLayoout.setOnRefreshListener(this);
        tvSwitchShop.setOnClickListener(this::otherViewClick);
        medicalShopmenmberManage.setOnClickListener(this::otherViewClick);
    }

    @Override
    protected void initData() {
        if (MyApplication.isLogin) {
            QueryDoctorIdentify();
            GetMedicationCompanyByDrId();

        }

    }

    private void GetMedicationCompanyByDrId() {
        if (MyApplication.LoginEntity!=null){
            NetServices.Factory.getService().GetMedicationCompanyByDrId(
                    MyApplication.LoginEntity.getUser().getDoctorId() + "", "3"
            ).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseComPleteObserver<MedicationCompanyEntity>(getContext(), false) {
                        @Override
                        protected void onSuccees(BaseEntity<MedicationCompanyEntity> t) throws Exception {
                            Log.d(TAG,"GetMedicationCompanyByDrId认证"+ t.getData().toString());
                            String name = t.getData().getName();
                            int roletype = t.getData().getType();
                            MyApplication.medicationCompanyEntity = t.getData();
                            //认证状态。0未认证；1认证中；2已认证；3认证失败
                            int doctorstus = t.getData().getCheckStatus();
                            if (doctorstus == 2) {
                                lvYouxuantuijian.setVisibility(View.VISIBLE);
                            }

                            RxBus.get().post(Event.getdoctor_info, true);

                            //认证状态。0未认证；1认证中；2已认证；3认证失败
                            switch (doctorstus) {
                                case 0:
                                    tvDoctorRenzheng.setText("未认证" + ",点击去认证");

                                    break;
                                case 1:
                                    tvDoctorRenzheng.setText("认证中");

                                    break;
                                case 2:
                                    tvDoctorRenzheng.setText("已认证");

                                    break;
                                case 3:
                                    tvDoctorRenzheng.setText("认证失败" + ",点击去认证");

                                    break;
                            }


                        }

                        @Override
                        protected void onFailure(Throwable e, String erroressage, boolean isNetWorkError) throws Exception {
                            super.onFailure(e, erroressage, isNetWorkError);
                            swipeLayoout.setRefreshing(false);
                        }
                    });
        }

    }

    @Override
    protected void otherViewClick(View view) {
        switch (view.getId()) {
            case R.id.login_out:
                logout();
                break;

            case R.id.tv_doctor_renzheng:
                Intent intent2 = new Intent(getContext(), RenzhengActivity.class);
                startActivity(intent2);
                break;
            case R.id.change_password:
                Intent changepassword = new Intent(getContext(), ChangePasswordActivity.class);
                startActivity(changepassword);
                break;
            case R.id.about_us:
                Intent aboutus = new Intent(getContext(), AboutUsActivity.class);
                startActivity(aboutus);

                //开始扫描二维码，并且返回二维码数据
//               // if (PermissionUtil.INSTANCE.checkPermissionStorage(getActivity())) {
//                    Intent intentscan = new Intent(getContext(), CaptureActivity.class);
//                    startActivityForResult(intentscan, 3);
//                //}
                break;
            case R.id.item_advice:
                Intent advice = new Intent(getContext(), SuggestionActivity.class);
                startActivity(advice);
                break;

            case R.id.item_callphone:
                //拨打电话（跳转到拨号界面，用户手动点击拨打）
//                Intent callphone = new Intent(Intent.ACTION_DIAL);
//                Uri data = Uri.parse("tel:" + "075582569787");
//                callphone.setData(data);
//                startActivity(callphone);
                Intent intentkefu = new Intent(getContext(), WebViewActivity.class);
                intentkefu.putExtra("type", 24);
                intentkefu.putExtra("Name", MyApplication.LoginEntity.getUser().getDoctorName() + "");
                intentkefu.putExtra("AccountId", MyApplication.LoginEntity.getUser().getDoctorId() + "");
                intentkefu.putExtra("Sex", MyApplication.LoginEntity.getUser().getSex() + "");
                intentkefu.putExtra("Mobile", MyApplication.LoginEntity.getUser().getMobile() + "");
                startActivity(intentkefu);

                break;
            case R.id.clear_cache:
                CleanMessageUtil.clearAllCache(getContext());
                ToastUtil.setToast("已经清除了" + totalCacheSize);
                getCache();
                setCatch();
                break;
            case R.id.item_renzheng:
                Intent renzheng = new Intent(getContext(), OrganizationInfoActivity.class);
                startActivity(renzheng);
                break;

            case R.id.siwtch_environment://切换正式环境，测试环境
                SwitchEnvironmentDialog switchEnvironmentDialog = new SwitchEnvironmentDialog(getContext());
                switchEnvironmentDialog.show(new SwitchEnvironmentDialog.DialogListener() {
                    @Override
                    public void switchTestEnv() {
                        //切换测试环境
                        EnvironmentManager.saveEnvironmentType(getContext(), EnvironmentManager.ENVIRONMENT_TEST);
                        SpUtils.clear();
                        initRetrofit();
                        SpUtils.put(Contants.IS_FIRST_USE, false);
                        Intent intent = new Intent(getContext(), LoginActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }

                    @Override
                    public void switchOnlineEnv() {
                        //切换正式环境
                        //切换测试环境
                        EnvironmentManager.saveEnvironmentType(getContext(), EnvironmentManager.ENVIRONMENT_ONLINE);
                        SpUtils.clear();
                        initRetrofit();
                        SpUtils.put(Contants.IS_FIRST_USE, false);
                        Intent intent = new Intent(getContext(), LoginActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);

                    }
                });
                break;

            case R.id.tv_switch_shop://切换门店

                Intent switchshop = new Intent(getContext(), SwitchShopActivity.class);
                startActivity(switchshop);
                break;
            case R.id.medical_shopmenmber_manage://切换门店

                //  ToastUtil.setToast("药店店员管理");
                Intent tiaopei = new Intent(getContext(), WebViewActivity.class);
                tiaopei.putExtra(Contants.TYPE, 36);
                getContext().startActivity(tiaopei);
                break;
        }
    }

    private void logout() {
        LogOutUtil.getInstance().loginOut(getContext(), true, 2);

    }

    private void QueryDoctorIdentify() {
        if (MyApplication.LoginEntity != null) {
            NetServices.Factory.getService().QueryDoctorIdentify(
                    MyApplication.LoginEntity.getUser().getDoctorId() + ""
            ).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseComPleteObserver<DoctorInfoEntity>(getContext(), false) {
                        @Override
                        protected void onSuccees(BaseEntity<DoctorInfoEntity> t) throws Exception {
                            Log.d(TAG, t.getData().toString());
                            if (t.getData() != null) {
                                MyApplication.DoctorInfoEntity = t.getData();
                                int roletype = t.getData().getRoleType();
                                MyApplication.LoginEntity.getUser().setRoleType(roletype);
                                String loginJson = SpUtils.getString(Contants.LoginJson);
                                if (!TextUtils.isEmpty(loginJson)) {
                                    H5LoginEntity h5LoginEntity = new Gson().fromJson(loginJson, H5LoginEntity.class);
                                    if (!h5LoginEntity.getDoctor().getData().getUser().getRoleType().equals(roletype + "")) {
                                        h5LoginEntity.getDoctor().getData().getUser().setRoleType(roletype + "");
                                        SpUtils.put(Contants.LoginJson, new Gson().toJson(h5LoginEntity));
                                        SpUtils.put(Contants.LoginInfo, new Gson().toJson(MyApplication.LoginEntity));
                                        RxBus.get().post(Event.mine_refresh, true);
                                    }
                                }

                                RxBus.get().post(Event.getdoctor_info, true);
                                swipeLayoout.setRefreshing(false);
                                //tvName.setText(t.getData().getDrName());
                                // 1老板，2医生，3老板并且是医生,4，药房  0啥都不是
                                //医生认证状态(认证状态。0未认证；1认证中；2已认证；3认证失败)  DrStatus

                                // 老板认证状态(认证状态。0未认证；1认证中；2已认证；3认证失败)

                                listall.clear();
                                listall.addAll(AppLicationUtils.getroletype(roletype));
                                mFunctionAdapter.setList(listall);
                                if (listall.size() == 0) {
                                    tvOrderTitle.setVisibility(View.GONE);
                                } else {
                                    tvOrderTitle.setVisibility(View.VISIBLE);
                                }
                                //切换门店显示
                                if (roletype == 12) {//12平台药师登陆不用显示切换门店，药店药师要切换门店  并且不显示认证状态
                                    tvSwitchShop.setVisibility(View.GONE);
                                    tvDoctorRenzheng.setText(t.getData().getDrRemark()+"");
                                } else {
                                    tvSwitchShop.setVisibility(View.VISIBLE);
                                }
                                //2/5/6/7/8/9/10/11/12显示账号名  2/5/6/7/8/9/10/11/12没有机构信息管理按钮  没有药店管理入口
                                if (roletype == 1||roletype == 2|| roletype == 3||roletype == 4|| roletype == 5 || roletype == 6 || roletype == 7 || roletype == 8 || roletype == 9 || roletype == 10 || roletype == 11 || roletype == 12) {
                                    lvShop.setVisibility(View.VISIBLE);
                                    String name = t.getData().getDrName();
                                    if (!TextUtils.isEmpty(name)) {
                                        if (name.length() > 14) {
                                            tvName.setText(name.substring(0, 8) + "..." + name.substring(name.length() - 6, name.length()));
                                        } else {
                                            tvName.setText(name);
                                        }
                                    }
                                    String shop = t.getData().getCompanyName();
                                    if (!TextUtils.isEmpty(shop)) {
                                        if (shop.length() > 14) {
                                            tvShop.setText(shop.substring(0, 8) + "..." + shop.substring(shop.length() - 6, shop.length()));
                                        } else {
                                            tvShop.setText(shop);
                                        }
                                    }

                                   // tvShop.setText((TextUtils.isEmpty(t.getData().getCompanyName()) ? "" : t.getData().getCompanyName()) + "");
                                } else {

                                    String name = t.getData().getCompanyName();
                                    if (!TextUtils.isEmpty(name)) {
                                        if (name.length() > 14) {
                                            tvName.setText(name.substring(0, 8) + "..." + name.substring(name.length() - 6, name.length()));
                                        } else {
                                            tvName.setText(name);
                                        }
                                    }else {
                                        String drname = t.getData().getDrName();
                                        if (!TextUtils.isEmpty(drname)) {
                                            if (drname.length() > 14) {
                                                tvName.setText(drname.substring(0, 8) + "..." + drname.substring(drname.length() - 6, drname.length()));
                                            } else {
                                                tvName.setText(drname);
                                            }
                                        }
                                    }
                                    lvShop.setVisibility(View.INVISIBLE);
                                }

                                //处理机构信息管理药店管理的显示
                                if (roletype == 1|| roletype == 3){   //只显示一个
                                    itemRenzheng.setVisibility(View.VISIBLE);
                                    jigouLine.setVisibility(View.VISIBLE);
                                }
                                if (roletype==4){//两个都显示
                                    itemRenzheng.setVisibility(View.VISIBLE);
                                    jigouLine.setVisibility(View.VISIBLE);
                                    medicalShopmenmberManage.setVisibility(View.VISIBLE);
                                    lineYaodian.setVisibility(View.VISIBLE);
                                }

                                if (roletype!=1&&roletype!=3&&roletype!=4){
                                    itemRenzheng.setVisibility(View.GONE);
                                    jigouLine.setVisibility(View.GONE);
                                    medicalShopmenmberManage.setVisibility(View.GONE);
                                    lineYaodian.setVisibility(View.GONE);
                                }

                                //6/7/8/9/10/11/12不用显示认证状态
                                if (roletype == 2 || roletype == 5 || roletype == 6 || roletype == 7 || roletype == 8 || roletype == 9 || roletype == 10 || roletype == 11) {
                                    tvDoctorRenzheng.setVisibility(View.GONE);
                                } else {
                                    tvDoctorRenzheng.setVisibility(View.VISIBLE);
                                }
                                //显示药店名称或者不显示药店名称
                                if (roletype == 1|| roletype == 3||roletype == 4||roletype == 2 || roletype == 5 || roletype == 6 || roletype == 7 || roletype == 8 || roletype == 9 || roletype == 10 || roletype == 11) {
                                    lvShop.setVisibility(View.VISIBLE);
                                } else {
                                    lvShop.setVisibility(View.INVISIBLE);
                                }

                                GlideUtils.loadDoctorImage(t.getData().getPicturePath(), imDoctor);
                            }
                        }

                        @Override
                        protected void onFailure(Throwable e, String erroressage, boolean isNetWorkError) throws Exception {
                            super.onFailure(e, erroressage, isNetWorkError);
                            swipeLayoout.setRefreshing(false);
                        }
                    });
        }
    }

    private String getCache() {
        try {
            totalCacheSize = CleanMessageUtil.getTotalCacheSize(getContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return totalCacheSize;

    }


    /**
     * 初始化网络请求的
     */
    private void initRetrofit() {

        String token = SpUtils.getString(Contants.Token);
        //开启抓包谷歌浏览器抓包
        String baseUrl;
        //获取当前是正式环境还是测试环境并且初始化网络

        if (BuildConfig.DEBUG) { //测试环境
            //判断是正式环境还是测试环境
            if (EnvironmentManager.isDebug(getContext())) {
                baseUrl = AppConfig.TEST_URL;
            } else {
                baseUrl = AppConfig.ONLINE_URL;
            }
            RetrofitFactory.getRetrofitFactory().init(getContext(), baseUrl, token);
            NetServices.Factory.create();

        } else { //正式环境
            AppConfig.TEST = false;
            RetrofitFactory.getRetrofitFactory().init(getContext(), AppConfig.ONLINE_URL, token);
            NetServices.Factory.create();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.get().unregister(Event.Login_success, loginObservable);
        RxBus.get().unregister(Event.Login_success, switchShopObservable);
    }

    @Override
    public void onRefresh() {
        if (MyApplication.isLogin) {
            QueryDoctorIdentify();
            GetMedicationCompanyByDrId();
        }

    }
}
